import React, { useState, useEffect, useRef, Suspense } from 'react';
import { Layout, Space, Spin, Button } from 'antd';
import { MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';

import { RouteConfigComponentProps, renderRoutes } from 'react-router-config';

import { logoutSys } from '../utils';
import { checkPermission } from '../permission/Index';
import { getStore } from 'store/store';
import UserArea from 'components/UserArea';
import DownloadModel from 'admin/components/DownloadModel';

import { UserNotice } from 'admin/components/UserNotice';
import CheckInOut from 'seats/components/CheckInOut';
import DeviceCheck from 'seats/components/DeviceCheck';

import SipComponent from 'components/SipComponent/SipComponent';
import { casMenuPermission, SideMenu } from './SideMenu';
import './BasicLayout.scss';
import { BreadCrumb } from './BreadCrumb';
import WebLogo from './WebLogo';
import BillingSystemLink from 'components/BillingSystemLink';
import { getCasUserInfo } from 'admin/servers/modules/Cas';
import { getPublicKey } from 'admin/servers/servers';
import { useSelector } from 'react-redux';
import { JSONObject } from 'admin/schema/common';
import { find, some, startsWith } from 'lodash';
import { useHistory } from 'react-router-dom';
const { Header, Content, Sider } = Layout;

const BasicLayout: React.FC<RouteConfigComponentProps> = props => {
  const history = useHistory();
  const loginInfo = useSelector((state: JSONObject) => state.loginInfo);
  const isUnMont = useRef<boolean>(false); // 防止内存溢出

  const [collapsed, setCollapsed] = useState<boolean>(false);
  const [canRender, setCanRender] = useState<boolean>(false);
  const [showDownload, setShowDownload] = useState<boolean>(false);
  const [isshow, setIsshow] = useState(true);

  const STORE = getStore();

  /**控制侧边栏显示/隐藏*/
  const toggleSider = () => setCollapsed(prev => !prev);
  /**
   * 控制头部icon抽屉，显示/隐藏
   */
  const toggleShow = (str: string) => {
    if (str === 'download') {
      // 打开-下载抽屉
      setShowDownload(true);
    } else {
      // 关闭-所有抽屉
      setShowDownload(false);
    }
  };
  /**渲染页面-全屏（机器人流程预览页面）*/
  useEffect(() => {
    STORE.addChangeEvent('isFullScreen', val => {
      toggleSider();
      setIsshow(prev => !prev);
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    getCasUserInfo({ username: loginInfo.username })
      .then(res => {
        if (res.status === 200) {
          setCanRender(true);
        } else {
          logoutSys(true);
        }
      })
      .catch(err => {
        console.log('BasicLayout组件-获取用户信息失败', err);
        logoutSys(true);
      });
  }, [loginInfo]);

  /**
   * 自动重定向
   */
  useEffect((): any => {
    if (!canRender) {
      // 页面不可见
      return;
    }
    // 测试过期天数函数，上线隐藏
    // checkValidate();
    let pathName = location.pathname;
    // 路径不是根路径，是以'.../'结尾，例如："/webapp/account/"，需要去掉末尾'/'
    if (pathName !== '/' && pathName.slice(-1) === '/') {
      pathName = pathName.slice(0, -1);
    }
    if (
      startsWith(pathName, '/webapp/casSystem') ||
      startsWith(pathName, '/webapp/casStatistics')
    ) {
      const target = find(loginInfo?.permissions, { code: casMenuPermission[pathName] });
      if (!target) {
        history.push('/401');
      }
    }

    return () => (isUnMont.current = true); // 卸载时回调
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [canRender, location.pathname, loginInfo]);

  /** 初始获取下加密公钥 */
  useEffect(() => {
    getPublicKey();
  }, []);

  return (
    <>
      {canRender ? (
        <Layout className={isshow ? 'page-layout not-full-page' : 'page-layout full-page'}>
          <Header className="layout-header">
            <div className="header-logo">
              <img src="/webapp/applogo.png" />
              <span>西安市综合短信发布平台</span>
            </div>
            {/* <Button
                type="primary"
                onClick={toggleSider}
                icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
              /> */}
            <UserArea />
            {/* <DownloadModel fn={toggleShow} visible={showDownload} /> */}
            {/* <DeviceCheck /> */}
            {/* {checkPermission('/seats/callTask') && <CheckInOut />} */}
            {/* <UserNotice />/ */}
            {/* {checkPermission('/billingSystem') && <BillingSystemLink />} */}
          </Header>

          <Layout>
            <Sider
              width={250}
              collapsible
              collapsedWidth="0"
              collapsed={collapsed}
              trigger={null}
              breakpoint="lg"
              theme="light"
            >
              <WebLogo />
              <SideMenu />
            </Sider>
            <SipComponent />
            <Layout className="right-layout">
              <BreadCrumb />
              <Content className="right-layout-content">
                <Suspense
                  fallback={
                    <Space direction="vertical" className="all-scre" align="center" size="middle">
                      <Spin size="default" />
                      <div>正在加载页面……</div>
                    </Space>
                  }
                >
                  {renderRoutes(props.route?.routes)}
                </Suspense>
              </Content>
            </Layout>
          </Layout>
        </Layout>
      ) : (
        <Space direction="vertical" className="all-scre" align="center" size="middle">
          <Spin size="default" />
          <div>正在加载权限数据</div>
        </Space>
      )}
    </>
  );
};

export default BasicLayout;
